<template>
  <div class="app-container">
    <h2 style="text-align: center">发布新课程</h2>
    <el-steps
      :active="2"
      process-status="wait"
      align-center
      style="margin-bottom: 40px"
    >
      <el-step title="填写课程基本信息" />
      <el-step title="创建课程大纲" />
      <el-step title="最终发布" />
    </el-steps>

    <!-- 课程章节查询 -->
    <el-input
      v-model="filterText"
      placeholder="Filter keyword"
      style="margin-bottom: 30px"
    />

    <!-- 章节添加按钮 -->
    <el-button type="text" @click="openChapterDialog()">添加章节</el-button>

    <!-- 课程章节展示 -->
    <div>
      <el-tree
        ref="tree2"
        :data="chapterVideoList"
        :props="defaultProps"
        :filter-node-method="filterNode"
        class="filter-tree"
        :render-content="renderContent"
        default-expand-all
      />
    </div>

    <el-form label-width="120px">
      <el-form-item>
        <el-button @click="previous">上一步</el-button>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="next"
          >下一步</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 添加和修改章节表单 -->
    <el-dialog :visible.sync="dialogChapterFormVisible" title="添加章节">
      <el-form :model="chapter" label-width="120px">
        <el-form-item label="章节标题">
          <el-input v-model="chapter.title" />
        </el-form-item>
        <el-form-item label="章节排序">
          <el-input-number
            v-model="chapter.sort"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogChapterFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加和修改课时表单 -->
    <el-dialog :visible.sync="dialogVideoFormVisible" title="添加课时">
      <el-form :model="video" label-width="120px">
        <el-form-item label="课时标题">
          <el-input v-model="video.title" />
        </el-form-item>
        <el-form-item label="课时排序">
          <el-input-number
            v-model="video.sort"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="是否免费">
          <el-radio-group v-model="video.isFree">
            <el-radio :label="1">免费</el-radio>
            <el-radio :label="0">默认</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上传视频">
          <el-upload
            :on-success="handleVodUploadSuccess"
            :on-remove="handleVodRemove"
            :before-remove="beforeVodRemove"
            :on-exceed="handleUploadExceed"
            :file-list="fileList"
            :action="BASE_API + '/eduVod/video/upLoadVideo'"
            :limit="1"
            class="upload-demo"
          >
            <el-button size="small" type="primary">上传视频</el-button>
            <el-tooltip placement="right-end">
              <div slot="content">
                最大支持1G，<br />
                支持3GP、ASF、AVI、DAT、DV、FLV、F4V、<br />
                GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、<br />
                MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB、<br />
                SWF、TS、VOB、WMV、WEBM 等视频格式上传
              </div>
              <i class="el-icon-question" />
            </el-tooltip>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelFormVisible">取 消</el-button>
        <el-button
          :disabled="saveVideoBtnDisabled"
          type="primary"
          @click="saveOrUpdateVideo"
        >
          确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import chapter from "@/api/edu/chapter";
import video from "@/api/edu/video";
export default {
  data() {
    return {
      filterText: "",
      saveBtnDisabled: false, // 保存按钮是否禁用
      courseId: "", // 所属课程id
      chapterVideoList: [], //所有章节与小节数据
      // 章节列表结构
      defaultProps: {
        children: "children",
        label: "title",
      },
      chapter: {
        //封装章节数据
        courseId: "",
        title: "",
        sort: 0,
      },
      video: {
        // 小节对象
        chapterId: "",
        courseId: "",
        title: "",
        sort: 0,
        isFree: 0,
        videoSourceId: "",
        videoOriginalName: "",
      },
      saveVideoBtnDisabled: false, // 课时按钮是否禁用
      dialogChapterFormVisible: false, //章节弹框
      dialogVideoFormVisible: false, //小节弹框
      BASE_API: process.env.BASE_API, //当前请求端口
      fileList: [], //上传文件列表
    };
  },
  created() {
    //初始化章节信息
    this.init();
  },

  methods: {
    //初始video对象
    cleanVideo() {
      (this.video.videoSourceId = ""), (this.video.videoOriginalName = "");
    },
    //********上传视频 **************/
    //上传视频成功
    handleVodUploadSuccess(response, file, fileList) {
      //上传视频id
      this.video.videoSourceId = response.data.videoId;
      //上传视频名称
      this.video.videoOriginalName = file.name;
    },
    //视图上传多于一个视频
    handleUploadExceed(files, fileList) {
      this.$message.warning("想要重新上传视频，请先删除已上传的视频");
    },
    //删除视频确定，执行的方法
    handleVodRemove(file, fileList) {
      console.log(file);
      video.deleteVideoByID(this.video.videoSourceId).then((response) => {
        this.$message({
          type: "删除视频成功",
          message: response.message,
        });
        //清空文件列表
        this.fileList = [];
        //清空video对象
        this.cleanVideo();
      });
    },
    //点击x删除视频的该方法
    beforeVodRemove(file, fileList) {
      //提示
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // ------------------ 小节操作  ----------------------
    //删除小节
    removeVidel(data) {
      this.$confirm("此操作将永久删除讲师记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          video
            .deleteVideo(data.id)
            .then((response) => {
              //提示信息
              this.$message({
                type: "success",
                message: "删除小节成功!",
              });
              //刷新数据
              this.getChapterVideo();
            })
            .catch((response) => {
              // 失败
              if (response === "cancel") {
                this.$message({
                  type: "info",
                  message: "已取消删除",
                });
              } else {
                this.$message({
                  type: "error",
                  message: response.message,
                });
              }
            });
        })
        .catch(() => {}); //点击取消，执行catch方法;;
    },
    //编辑小节
    appendVideo(data) {
      this.dialogVideoFormVisible = true;
      console.log(data);
      video.getVideoInfoById(data.id).then((response) => {
        this.video = response.data.eduVideInfo;
        //回显上传视频
        if (this.video.videoOriginalName != "") {
          this.fileList = [{ name: this.video.videoOriginalName }];
        }
      });
    },
    //取消提交表单
    cancelFormVisible() {
      this.dialogVideoFormVisible = false;
      this.fileList = [];
    },
    //保存或者更新章节
    saveOrUpdateVideo() {
      if (!this.video.id) {
        this.addVideo();
        this.fileList = [];
      } else {
        this.updateVideo();
      }
    },
    //更新小节
    updateVideo() {
      video
        .updateVideoInfo(this.video)
        .then((response) => {
          //关闭弹窗
          this.dialogVideoFormVisible = false;
          //提示
          this.$message({
            type: "success",
            message: "更新成功!",
          });
          //更新后清空chapter.id
          this.video.id = null;
          //刷新数据
          this.getChapterVideo();
        })
        .catch((response) => {
          this.$message({
            type: "error",
            message: "更新失败!",
          });
        });
    },
    //添加小节
    addVideo() {
      //设置课程id
      this.video.courseId = this.courseId;
      console.log(this.video);
      //当前课程id存放到video
      video
        .addVideo(this.video)
        .then((response) => {
          this.dialogVideoFormVisible = false;
          this.$message({
            type: "success",
            message: "添加小节成功",
          });

          this.getChapterVideo();
        })
        .catch((response) => {
          this.$message({
            type: "error",
            message: "添加失败!",
          });
        });
    },
    //打开小节弹框
    openVideo(data) {
      console.log(data);

      //清除数据
      this.video = {
        chapterId: "",
        courseId: "",
        title: "",
        sort: 0,
        free: 0,
        videoSourceId: "",
      };
      //设置章节id
      this.video.chapterId = data.id;
      console.log("chapterId:" + this.video.chapterId);

      this.dialogVideoFormVisible = true;
    },
    //------------------ 章节操作 ---------------------------------
    //删除章节
    removeChapter(data) {
      this.$confirm("此操作将永久删除讲师记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          chapter
            .deleteChapter(data.id)
            .then((response) => {
              //提示信息
              this.$message({
                type: "success",
                message: "删除章节成功!",
              });
              //刷新数据
              this.getChapterVideo();
            })
            .catch((response) => {
              // 失败
              if (response === "cancel") {
                this.$message({
                  type: "info",
                  message: "已取消删除",
                });
              } else {
                this.$message({
                  type: "error",
                  message: response.message,
                });
              }
            });
        })
        .catch(() => {}); //点击取消，执行catch方法;
    },
    //编辑章节
    appendChapter(data) {
      this.dialogChapterFormVisible = true;
      console.log(data.id);
      chapter.getChapterById(data.id).then((response) => {
        this.chapter = response.data.eduChapter;
      });
    },
    //树节点内容的自定义
    renderContent(h, { node, data, store }) {
      //判断该数据是小节还是章节
      if (!data.children) {
        return (
          <span class="custom-tree-node">
            <span>{node.label}</span>
            <span>
              <el-button
                size="mini"
                type="text"
                style="right"
                on-click={() => this.appendVideo(data)}
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                on-click={() => this.removeVidel(data)}
              >
                删除
              </el-button>
            </span>
          </span>
        );
      } else {
        return (
          <span class="custom-tree-node">
            <span>{node.label}</span>
            <span>
              <el-button
                size="mini"
                type="text"
                style="right"
                on-click={() => this.openVideo(data)}
              >
                添加小节
              </el-button>
              <el-button
                size="mini"
                type="text"
                style="right"
                on-click={() => this.appendChapter(data)}
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                on-click={() => this.removeChapter(data)}
              >
                删除
              </el-button>
            </span>
          </span>
        );
      }
    },
    saveOrUpdate() {
      if (!this.chapter.id) {
        this.addChapter();
      } else {
        this.updateChapter();
      }
    },
    //更新章节
    updateChapter() {
      chapter
        .updateByIds(this.chapter)
        .then((response) => {
          //关闭弹窗
          this.dialogChapterFormVisible = false;
          //提示
          this.$message({
            type: "success",
            message: "更新成功!",
          });
          //更新后清空chapter.id
          this.chapter.id = null;
          //刷新数据
          this.getChapterVideo();
        })
        .catch((response) => {
          this.$message({
            type: "error",
            message: "更新失败!",
          });
        });
    },
    //添加章节
    addChapter() {
      console.log(this.chapter);
      chapter
        .addChapter(this.chapter)
        .then((response) => {
          //关闭弹窗
          this.dialogChapterFormVisible = false;
          //提示
          this.$message({
            type: "success",
            message: "保存成功!",
          });
          //刷新数据
          this.getChapterVideo();
        })
        .catch((response) => {
          this.$message({
            type: "error",
            message: "添加失败!",
          });
        });
    },
    //弹出添加章节页面
    openChapterDialog() {
      //弹框
      this.dialogChapterFormVisible = true;
      //表单数据清空
      this.chapter.title = "";
      this.chapter.sort = 0;
    },
    //初始化章节信息
    init() {
      if (this.$route.params && this.$route.params.id) {
        this.courseId = this.$route.params.id;
        this.chapter.courseId = this.$route.params.id;

        // 根据id获取课程基本信息
        this.getChapterVideo();
      }
    },
    //根据课程id，查询章节与小节信息
    getChapterVideo() {
      chapter
        .addCourseInfo(this.courseId)
        .then((response) => {
          this.chapterVideoList = response.data.allChapterVideo;
        })
        .catch((response) => {
          this.$message({
            type: "error",
            message: response.message,
          });
        });
    },

    previous() {
      console.log("previous");
      this.$router.push({ path: "/course/info/" + this.courseId });
    },
    next() {
      console.log("next");
      this.$router.push({ path: `/course/publish/${this.courseId}` });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.title.toLowerCase().indexOf(value) !== -1;
    },
  },
};
</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>